package com.xmxsuperstar.http;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.List;

import net.love5z.common.json.JSONObject;

import com.xmxsuperstar.app.CommonConstants;

public abstract class HttpMsg implements Serializable {

	private static final long serialVersionUID = 1L;

	private HttpHeaders httpHeaders = new HttpHeaders();

	private byte[] body = new byte[0];

	public HttpMsg() {

	}

	public void addHeader(String headerName, String headerValue) {
		httpHeaders.add(headerName, headerValue);
	}

	public List<String> getHeader(String headerName) {
		return httpHeaders.get(headerName);
	}

	public List<String> fetchAllHeaderNames() {
		return httpHeaders.fetchAllHeaderNames();
	}

	public HttpHeaders getAllHeaders() {
		return this.httpHeaders;
	}

	public void setBody(byte[] body) {
		if (body == null) {
			this.body = new byte[0];
		} else {
			this.body = body;
		}
	}

	public byte[] fetchBody() {
		return this.body;
	}

	public String getBodyText() {
		String res = null;
		try {
			// Content-Type: text/html; charset=utf-8
			String charSet = CommonConstants.CHAR_ENCODING;
			if (this.getHeader("Content-Type").size() > 0) {
				String contentType = this.getHeader("Content-Type").get(0);

				if (MIMEUtils.isTextType(contentType)) {
					if (contentType.contains(";")) {
						charSet = contentType.split(";")[1].trim().split("=")[1]
								.trim();
					}
				} else {
					// not text body
					return null;
				}

			}
			res = new String(this.fetchBody(), charSet);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return res;
	}

	@Override
	public String toString() {
		return new JSONObject(this).toString();
	}
}
